﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PccCommonForC;
using System.Xml;
using System.IO;

public partial class Shopping_Basket_Basket : System.Web.UI.Page
{
    int pQuantity = 0;
    decimal pTotal = 0;
    protected decimal pMoneyRate = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
            
        if (!IsPostBack)
        {
            BindData();
            lblOrder.Text = " Bạn phải có tài khoản tại <b>" + System.Configuration.ConfigurationManager.AppSettings["AppName"] + " </b>thì mới có thể hoàn tất đơn đặt hàng.";
        }
        if (Request.QueryString["KindNo"] == "F")
            btnCapNhatFilm.Visible = true;      
        if (grv_Master.Rows.Count <= 0)
        {
            btnCapNhat.Visible = false;
            btnTraHang.Visible = false;
            pnBooksPD.Visible = false;
            btnCapNhatFilm.Visible = false;
        }
        


    }


    private void BindData()
    {
        grv_Master.DataSource = GetData();
        grv_Master.DataBind();
    }

    private DataTable GetData()
    {
        if (Request.QueryString["KindNo"] == "")
            return new DataTable();

        DataTable dtBasket = new DataTable();
        DataTable dt = new DataTable();
        string sSession = "dtBasket";
        if(Request.QueryString["KindNo"]=="F")
            sSession = "dtBasketFilm";
        if (Session[sSession] != null)
        {
            dtBasket = (DataTable)Session[sSession];
            clsWebShop cls = new clsWebShop();
            decimal USD = cls.GetMoney("USD");
            lblUSD.Text = "Tỉ giá USD: " + FormatMoney(USD) + " VNĐ";
            pMoneyRate = USD;
            DataRow dr;
            dt.Columns.Add(new DataColumn("PDID"));
            dt.Columns.Add(new DataColumn("PDName"));
            dt.Columns.Add(new DataColumn("Price"));
            dt.Columns.Add(new DataColumn("Quantity"));
            dt.Columns.Add(new DataColumn("Rate"));
            dt.Columns.Add(new DataColumn("KindNo"));
            dt.Columns.Add(new DataColumn("Total"));

            for (int i = 0; i < dtBasket.Rows.Count; i++)
            {
                dr = dt.NewRow();
                dr[0] = dtBasket.Rows[i]["PDID"].ToString();
                dr[1] = dtBasket.Rows[i]["PDNAME"].ToString();
                dr[2] = dtBasket.Rows[i]["PRICE"].ToString();
                dr[3] = dtBasket.Rows[i]["QUANTITY"].ToString();
                dr[4] = dtBasket.Rows[i]["RATE"].ToString();
                dr[5] = dtBasket.Rows[i]["KINDNO"].ToString();
                decimal ThanhTien = int.Parse(dtBasket.Rows[i]["QUANTITY"].ToString()) * decimal.Parse(dtBasket.Rows[i]["PRICE"].ToString());
                if (dtBasket.Rows[i]["RATE"].ToString() == "USD")
                    ThanhTien = ThanhTien * USD;
                dr[6] = ThanhTien.ToString();
                dt.Rows.Add(dr);
            }
        }
        return dt;
    }



    protected void grv_Master_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int index = e.RowIndex;
        DataTable dtBasket = new DataTable();
        string sSession = "dtBasket";
        if (Request.QueryString["KindNo"] == "F")
            sSession = "dtBasketFilm";
        if (Session[sSession] != null)
        {
            dtBasket = (DataTable)Session[sSession];
            if (dtBasket.Rows.Count > 0)
            {
                if (index != -1)
                {
                    dtBasket.Rows[index].Delete();
                }
            }
        }
        BindData();
    }
    protected void grv_Master_RowDataBound(object sender, GridViewRowEventArgs e)
    {       
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            pQuantity += int.Parse(DataBinder.Eval(e.Row.DataItem, "Quantity").ToString());
            pTotal += decimal.Parse(DataBinder.Eval(e.Row.DataItem, "Total").ToString());

            Label lblDongia = (Label)e.Row.FindControl("lblDongia");
            lblDongia.Text = FormatMoney(lblDongia.Text);

            Label lblThanhTien = (Label)e.Row.FindControl("lblThanhTien");
            lblThanhTien.Text = FormatMoney(lblThanhTien.Text);

            TextBox txtSoLuong = (TextBox)e.Row.FindControl("txtSoLuong");
            if (DataBinder.Eval(e.Row.DataItem, "KindNo").ToString() != "P")
            {
                txtSoLuong.ReadOnly = true;
                txtSoLuong.CssClass = "txt_ReadOnly";

                //Free
                lblThanhTien.Text = "Free";
                lblDongia.Text = "Free";
                Label lblKindMoney = (Label)e.Row.FindControl("lblKindMoney");
                lblKindMoney.Visible = false;

            }
            e.Row.Attributes.Add("onmouseover", "this.className='ItemHover_Basket'");
            e.Row.Attributes.CssStyle.Add("cursor", "pointer");
            e.Row.Attributes.Add("onmouseout", "this.className='ItemOut_Basket'");


        }
        else if (e.Row.RowType == DataControlRowType.Footer)
        {
            Label lblsl = new Label();
            Label lbltt = new Label();
            Label lblVND = new Label();
            lblsl.ID = "lblSL";
            lblsl.CssClass = "cssTongFSL";
            lblsl.Text = pQuantity.ToString();
            lbltt.ID = "lblTT";
            lbltt.CssClass = "cssTongFTien";
            lbltt.Text = FormatMoney(pTotal.ToString());
            lblVND.Text = "<b>$</b>";
            e.Row.Cells[0].Text = "<b>Tổng cộng</b>";
            e.Row.Cells[0].ColumnSpan = 3;
            e.Row.Cells[4].Controls.Add(lblsl);
            e.Row.Cells[5].Controls.Add(lblVND);
            e.Row.Cells[5].Controls.Add(lbltt);
            e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Left;
            e.Row.Cells[4].HorizontalAlign = HorizontalAlign.Center;
            e.Row.Cells[5].HorizontalAlign = HorizontalAlign.Right;    

            e.Row.Cells.RemoveAt(1);
            e.Row.Cells.RemoveAt(1);
            e.Row.Cells.RemoveAt(1);
        }
    }
    protected void btnCapNhat_Click(object sender, EventArgs e)
    {
        string sSession = "dtBasket";
        if (Request.QueryString["KindNo"] == "F")
            sSession = "dtBasketFilm";
        DataTable dtBasket = new DataTable();
        if (Session[sSession] != null)
        {
            dtBasket = (DataTable)Session[sSession];
        }

        for (int i = 0; i < grv_Master.Rows.Count; i++)
        {
            Label lblDonGia = (Label)grv_Master.Rows[i].FindControl("lblDonGia");
            TextBox txtSoLuong = (TextBox)grv_Master.Rows[i].FindControl("txtSoLuong");
            Label lblThanhTien = (Label)grv_Master.Rows[i].FindControl("lblThanhTien");
            if (int.Parse(txtSoLuong.Text) < 0)
            {
                ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Nhập đúng số lượng')</script>");
                grv_Master.FooterRow.Cells.RemoveAt(1);
                grv_Master.FooterRow.Cells.RemoveAt(1);
                grv_Master.FooterRow.Cells.RemoveAt(1);
                txtSoLuong.Focus();
                return;
            }
            else
            {
                dtBasket.Rows[i]["QUANTITY"] = txtSoLuong.Text;
            }
        }
        Session[sSession] = dtBasket;
        BindData();
    }
    protected void btnDatHang_Click(object sender, EventArgs e)
    {

        // Response.Redirect("../Order/OrderDetail.aspx");
        Response.Redirect(ResolveUrl("~/") + "Order/"+Request.QueryString["KindNo"]+".aspx");

    }
    protected void btnTraHang_Click(object sender, EventArgs e)
    {
        ClearSessionShopping();
        BindData();
        Response.Redirect(Request.UrlReferrer.AbsoluteUri.ToString());
    }
    private void ClearSessionShopping()
    {
        string sSession = "dtBasket";
        if (Request.QueryString["KindNo"] == "F")
            sSession = "dtBasketFilm";
        Session[sSession] = null;
    }
    protected void btnTiepTuc_Click(object sender, EventArgs e)
    {
        /*clsCommon cls = new clsCommon();
        string strUrl = cls.ResponsePageFile(Request.QueryString["pagefile"]);*/
        Response.Redirect(ResolveUrl("~/Shopping/Stall/Stall.aspx"));
    }

    private string FormatMoney(string sNum)
    {
        string sReturn = "0";
        try
        {
            sReturn = string.Format("{0:###,###,##0}", decimal.Parse(sNum));
        }
        catch (Exception) { }
        return sReturn;
    }


    private string FormatMoney(decimal dNum)
    {
        string sReturn = "0";
        try
        {
            sReturn = string.Format("{0:###,###,##0}", dNum);
        }
        catch (Exception) { }
        return sReturn;
    }

    private void PrintTable()
    {
        clsWebShop cls = new clsWebShop();
        Table tbl = new Table();
        DataTable dt = (DataTable)Session["dtBasketFilm"];

        string Css = "tbl2_trHeader";
        TableRow row = new TableRow();
        CreateRow(row, "Mã số", Css);
        CreateRow(row, "Tên phim", Css);
        CreateRow(row, "Dung lượng", Css);
        tbl.Rows.Add(row);

        for (int i = 0; i < dt.Rows.Count; i++)
        {

            string MaSo = "";
            PccMsg msg = new PccMsg();
            msg.CreateFirstNode("PDID", dt.Rows[i]["PDID"].ToString());
            DataTable dtPr = cls.Get_pd_PropertyDetailByCondition_NonePro(msg.GetXmlStr).Tables[0];
            if (dtPr.Rows.Count > 0)
            {
                MaSo = dtPr.Rows[0]["PrtdDesc"].ToString();
            }
            Css = i % 2 == 0 ? "tbl2_trRow" : "";

            row = new TableRow();
            CreateRow(row, MaSo, Css);
            CreateRow(row, dt.Rows[i]["PDNAME"].ToString(), Css);
            CreateRow(row, dt.Rows[i]["CAPACITY"].ToString(), Css);
            tbl.Rows.Add(row);         
        }
        ExportExcel(tbl);

    }
    private void CreateRow(TableRow row,string sText,string Css)
    {
        TableCell cell = new TableCell();
        cell.Text = sText;
        cell.CssClass = Css;
        cell.BorderWidth = 1;
        row.Cells.Add(cell);
    }


    private void ExportExcel(Table tbl)
    {
        tbl.EnableViewState = false;       
        Response.Clear();
        Response.Buffer = true;       
        Response.Charset = "utf-8";
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");

        Response.AppendHeader("Content-disposition", "attachment;filename=ListFilm-" + System.DateTime.Now.ToString("ddMMyyyyhhmmss") + ".xls");
        Response.ContentType = "application/vnd.ms-excel";// "application/x-msexcel";
        // 'Turn off the view state.
        //this.EnableViewState = false;

        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
        hw.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\" \nxmlns=\"http://www.w3.org/TR/REC-html40\">");
        hw.WriteFullBeginTag("HEAD");
        hw.Write("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
        string CSS_PhysicalPath = ResolveUrl("~/") + "Pub/Css/ExportStyles.css";

        if (CSS_PhysicalPath != null)
        {
            hw.RenderBeginTag(HtmlTextWriterTag.Style);
            hw.Write("<!--");

            StreamReader sr = File.OpenText(Server.MapPath(CSS_PhysicalPath));
            String input;
            while ((input = sr.ReadLine()) != null)
            {
                hw.WriteLine(input);
            }
            sr.Close();
            hw.Write("-->");
            hw.RenderEndTag();
        }

        hw.WriteEndTag("HEAD");
        hw.WriteFullBeginTag("BODY");

        hw.WriteEndTag("HEAD");
        hw.WriteFullBeginTag("BODY");


        tbl.RenderControl(hw);
        hw.WriteEndTag("BODY");
        hw.WriteEndTag("HTML");
        Response.Write(tw.ToString());
        Response.Flush();
        Response.End();
    }



    protected void btnCapNhatFilm_Click(object sender, EventArgs e)
    {
       
    }
    protected void btnCapNhatFilm_Click1(object sender, EventArgs e)
    {
        PrintTable();
    }
}
